package com.liyuci.core.service;

import com.liyuci.core.dao.IBaseDao;
import com.liyuci.core.helper.BlankHelper;
import com.liyuci.core.helper.JpaReflectHelper;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

/**
 * 基础Service实现.
 * @author liyuci
 * @date Oct 18, 2017 4:15:32 PM
 */
public class BaseService<T> implements IService<T>
{
	@Autowired
	private IBaseDao<T, String> baseDao;
	@Autowired
	private EntityManager entityManager;
	
	@Override
	public void delete(String id)
	{
		//需要修改为软删除
		//this.baseDao.delete(id);
	}
	
	@Override
	public void delete(T t)
	{
		//需要修改为软删除
		//this.baseDao.delete(t);
	}
	
	@Override
	public void deleteForHard(String id)
	{
		
	}

	@Override
	public void deleteForHard(T t)
	{
		
	}
	
	@Override
	public T getOne(String id)
	{
		return this.baseDao.findOne(id);
	}
	
	@Override
	public Page<T> list(Pageable pageable)
	{
		return this.baseDao.findAll(pageable);
	}
	
	@Override
	public T saveOrUpdate(T t)
	{
		return this.baseDao.save(t);
	}

	@Override
	public List<T> listAll(String sortFieldName, Direction sortDirection)
	{
		if(BlankHelper.isBlank(sortDirection))
		{
			sortDirection = Direction.ASC;
		}
		
		if(BlankHelper.isNotBlank(sortFieldName)
				&& JpaReflectHelper.modelIsExistField(getTClass(), sortFieldName))
		{
			List<Sort.Order> list = new ArrayList<Sort.Order>();
	        Sort.Order order = new Sort.Order(sortDirection, sortFieldName);
	        list.add(order);
	        Sort sort = new Sort(list);
			return this.baseDao.findAll(sort);
		}
		return this.baseDao.findAll();
	}
	
	/**
	 * 获取泛型T的类型
	 * @author liyuci
	 * @date 2018-02-05 18:37:37
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Class<?> getTClass()
	{
		Class<? super T> clazz = (Class <T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		return clazz;
	}

	@Override
	public List<T> listAllByFieldName(String fieldName, String fieldValue)
	{
		Class<?> clazz = getTClass();
		//判断表是否存在“sortOrder”字段，1、如果存在就按照“sortOrder”的升序进行排列
		if(JpaReflectHelper.modelIsExistField(clazz, "sortOrder"))
		{
			return listAllByFieldName(fieldName, fieldValue, "sortOrder", Direction.ASC);
		}
		//2、判断是否存在“createDate”字段信息，如果存在就按照“createDate”的倒序进行排列
		else if(JpaReflectHelper.modelIsExistField(clazz, "createDate"))
		{
			return listAllByFieldName(fieldName, fieldValue, "createDate", Direction.DESC);
		}
		//3、默认按照“id”的升序进行排列
		return listAllByFieldName(fieldName, fieldValue, "id", Direction.ASC);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> listAllByFieldName(String fieldName, String fieldValue, String sortFieldName, Direction sortDirection)
	{
		Class<?> clazz = getTClass();
		if(JpaReflectHelper.modelIsExistField(clazz, fieldName))
		{
			String jpsl = "from " + clazz.getSimpleName() + " where " + fieldName + "=?1 ";
			//是否在数据库中存在排序字段
			boolean isExistSortFieldFlag = JpaReflectHelper.modelIsExistField(clazz, sortFieldName);
			if(isExistSortFieldFlag)
			{
				jpsl += " order by ?2 ";
				if(sortDirection.equals(Direction.ASC))
				{
					jpsl += " asc";
				}
				else
				{
					jpsl += " desc";
				}
			}
			Query query = entityManager.createQuery(jpsl);
			query.setParameter(1, fieldValue);
			if(isExistSortFieldFlag)
			{
				query.setParameter(2, sortFieldName);
			}
			return query.getResultList();
		}
		return new ArrayList<>();
	}

	@Override
	public List<T> listAllByFieldNameOrderBySortOrderAsc(String fieldName, String fieldValue)
	{
		return listAllByFieldName(fieldName, fieldValue, "sortOrder", Direction.ASC);
	}

	@Override
	public List<T> listAllByFieldNameOrderBySortOrderDesc(String fieldName, String fieldValue)
	{
		return listAllByFieldName(fieldName, fieldValue, "sortOrder", Direction.DESC);
	}

	@Override
	public List<T> listAllByFieldNameOrderByCreateDateAsc(String fieldName, String fieldValue)
	{
		return listAllByFieldName(fieldName, fieldValue, "createDate", Direction.ASC);
	}

	@Override
	public List<T> listAllByFieldNameOrderByCreateDateDesc(String fieldName, String fieldValue)
	{
		return listAllByFieldName(fieldName, fieldValue, "createDate", Direction.DESC);
	}

	@Override
	public List<T> listAllOrderBySortOrderAsc()
	{
		return listAll("sortOrder", Direction.ASC);
	}

	@Override
	public List<T> listAllOrderBySortOrderDesc()
	{
		return listAll("sortOrder", Direction.DESC);
	}

	@Override
	public List<T> listAllOrderByCreateDateAsc()
	{
		return listAll("createDate", Direction.ASC);
	}

	@Override
	public List<T> listAllOrderByCreateDateDesc()
	{
		return listAll("createDate", Direction.DESC);
	}
	
}
